﻿namespace ApiTemplate.WebApi.Filter
{
    /// <summary>
    /// 全局权限过滤器
    /// </summary>
    public class GlobalAuthorizationAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 方法执行之前进行拦截
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var endpoint = context.HttpContext.GetEndpoint();
            if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() == null)
            {
                string token = context.HttpContext.Request.Headers["BaseToken"];
                if (string.IsNullOrEmpty(token))
                {
                    throw new BusinessException
                    {
                        Code = ErrorCode.UnAuthorized,
                        ErrorMessage = "未授权的请求"
                    };
                }
                token = EncryptionHelper.Base64Decrypt(token);
                string[] arr = token.Split("{:}");
                string requestTime = arr[0];
                string key = arr[1];
                var appSetting = ConfigHelper.GetAppSetting();
                if (appSetting.Token != key)
                {
                    throw new BusinessException
                    {
                        Code = ErrorCode.UnAuthorized,
                        ErrorMessage = "未授权的请求"
                    };
                }
                int tokenExpire = appSetting.TokenExpire;
                if ((DateTime.FromFileTime(long.Parse(requestTime)) - DateTime.Now).Seconds > tokenExpire)
                {
                    throw new BusinessException
                    {
                        Code = ErrorCode.UnAuthorized,
                        ErrorMessage = "授权信息已过期"
                    };
                }
            }

            base.OnActionExecuting(context);
        }
    }
}
